import React, { useState, useEffect, useCallback } from 'react';
import { DatePicker, Spin } from 'antd';
import { Column } from '@ant-design/charts';
import moment from 'moment';
import { flatTryCatch } from '../../../servers/http';
import { homeStatisticByBureau } from 'admin/servers/servers';

const { RangePicker } = DatePicker;

const nameMap = {
  hangduan: '行业短信',
  fence: '靶向短信',
  intelligencecallCall: '智能外呼',
};

const FourthBureau: React.FC = () => {
  // 参数
  const [momentRange, setMomentRange] = useState<any>([
    moment().startOf('week'),
    moment().endOf('week'),
  ]);
  const [loading, setLoading] = useState(false);

  // 数据
  const [statisticBureau, setStatisticBureau] = useState<any>({
    data: [],
    xField: 'office',
    yField: 'value',
    seriesField: 'category',
    isGroup: true, // 分组柱状图
    color: ['#1890ff', '#13c2c2', '#722ed1'],
    xAxis: { label: { autoRotate: false } },
    yAxis: {
      label: { formatter: v => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') },
    },
    legend: { position: 'top' },
    tooltip: { shared: true },
    columnWidthRatio: 0.3, // 柱子宽度比例（0-1之间，越小柱子越细）
    marginRatio: 0.2, // 分组间距比例（可选）
  });

  // 处理数据
  const handleData = useCallback((allData: any) => {
    // 转成[key, value]，key就是三个项目名字，value是数据
    // value再转需要的格式
    // 最后是一个二维数组，用flatMap转成一维的
    const transData = Object.entries(allData)
      .map(([key, value]: any) =>
        value.map(({ jubanName, value }) => ({
          office: jubanName,
          category: nameMap[key],
          value,
        }))
      )
      .flatMap(item => item);
    setStatisticBureau(prev => ({
      ...prev,
      data: transData,
    }));
  }, []);

  // 请求数据
  const fetchData = useCallback(async () => {
    if (!momentRange || !momentRange.length) return;

    const params = {
      beginTime: momentRange[0].format('YYYY-MM-DD'),
      endTime: momentRange[1].format('YYYY-MM-DD'),
    };
    setLoading(true);
    const { response, error } = await flatTryCatch(homeStatisticByBureau(params));
    setLoading(false);
    if (error) return;
    handleData(response.data);
  }, [handleData, momentRange]);

  // 加载数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 处理时间范围变化
  const handleRangeChange = (dates, dateStrings) => {
    setMomentRange(dates);
  };

  return (
    <div className="single-item">
      <RangePicker
        allowClear={false}
        value={momentRange}
        onChange={handleRangeChange}
        format="YYYY-MM-DD"
      />
      <Spin spinning={loading}>
        <Column {...statisticBureau} height={400} />
      </Spin>
    </div>
  );
};

export default FourthBureau;
